package com.meitianhui.convenitenbuy.module.home.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseToolbarActivity;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.http.ResponseObserver;
import com.meitianhui.convenitenbuy.main.model.event.PayJumpBean;
import com.meitianhui.convenitenbuy.module.home.contract.SubmitOrderContract;
import com.meitianhui.convenitenbuy.module.home.di.DaggerHomeComponent;
import com.meitianhui.convenitenbuy.module.home.di.HomeModule;
import com.meitianhui.convenitenbuy.module.home.presenter.SubmitOrderPresenter;
import com.meitianhui.convenitenbuy.module.mine.http.MineApiDataSource;
import com.meitianhui.convenitenbuy.module.mine.model.ConsumerAddress;
import com.meitianhui.convenitenbuy.module.mine.ui.activity.ReceivingAddressActivity;
import com.meitianhui.convenitenbuy.module.wallet.model.PayResultBean;
import com.meitianhui.convenitenbuy.util.AddressUtil;
import com.meitianhui.convenitenbuy.util.EmptyUtil;
import com.meitianhui.convenitenbuy.util.GlideUtils;
import com.meitianhui.convenitenbuy.util.PreferenceUtils;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.util.SpannableEditor;
import com.meitianhui.convenitenbuy.util.StringUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by amy on 2018/1/9.
 */

public class SubmitOrderActivity extends BaseToolbarActivity
        implements RadioGroup.OnCheckedChangeListener ,SubmitOrderContract.View{

    private TextView mTvSubmitAdsName;
    private TextView mTvSubmitAdsPhone;
    private TextView mTvSubmitAdsAddress;
    private RelativeLayout mRlSubmitAddAddress;

    private ImageView ivGoodsPic;
    private TextView tvGoodsTitle;
    private TextView tvGoodsAttrs;
    private TextView tvGoodsMoney;
    private TextView tvGoodsNumber;
    private ImageView ivGoodsMinus;
    private ImageView ivGoodsPlus;

    private TextView mTvSubmitMessage;
    private TextView tvPaymentInfo;
    private TextView mTvSubmitPayable,mTvSubmitGoPay;
    private RadioButton mRbSubmitAlipay;
    private RadioButton mRbSubmitWxpay;
    private RadioGroup mRgOrderPay;
    private List<ConsumerAddress.ConsumerData> consumerDataList;
    @Inject
    SubmitOrderPresenter mSubmitOrderPresenter;

    private String mPayWay = Constants.ALIPAY_APY;//默认支付宝支付
    private String mOrderType;
    private String mGoods_code;
    private String mAmount;
    private String mOrderId;
    private String mData_source;
    private String quantity;        // 下单的商品个数
    private String saleQty;         // 库存商品数量
    private String discountPrice;   // 优惠后的金额
    private String skuId;
    private boolean flags;

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        setTbTitle("提交订单");
        isEnable(false);
        DaggerHomeComponent.builder()
                .appComponent(App.getInstance().getAppComponent())
                .homeModule(new HomeModule(this))
                .build()
                .inject(this);
        initId();
        showData();
        initListener();
        registerPush();
    }

    private void registerPush() {
        Disposable subscribe = RxBus.get().toFlowable(PayResultBean.class).subscribe(new Consumer<PayResultBean>() {
            @Override
            public void accept(PayResultBean payResultBean) throws Exception {
                if (payResultBean.result == Constants.PAY_RESULT_SUCCESS | payResultBean.result == Constants.PAY_RESULT_FAIL_HUIGUO ) {
                    //微信支付成功后，要关闭提交订单的界面
                    finish();
                    if ("meitianhui".equals(mData_source)){
                        RxBus.get().post(new PayJumpBean("meitianhui"));
                    }else {
                        RxBus.get().post(new PayJumpBean("huiguo"));
                    }

                }
            }
        });
        mCompositeDisposable.add(subscribe);
    }

    private void initListener() {
        mRgOrderPay.setOnCheckedChangeListener(this);
    }

    private void showData() {
        //展示数据
        Intent intent = getIntent();
        String json = intent.getStringExtra("value");
        mOrderId = intent.getStringExtra("from");

        try {
            JSONObject jsonObject = new JSONObject(json);
            mGoods_code = jsonObject.optString("goods_code");
            mAmount = jsonObject.optString("amount");
            discountPrice = jsonObject.optString("discount_price");
            mData_source = jsonObject.optString("data_source");
            saleQty = jsonObject.optString("sale_qty");
            flags = jsonObject.optBoolean("flags");
            skuId = jsonObject.optString("sku_id");
            quantity = jsonObject.optString("quantity");
            if (StringUtils.isBlank(quantity)) quantity = "1";

            String title = jsonObject.optString("title");
            String pic_info_url = jsonObject.optString("thumb_pic");
            String zValue = jsonObject.optString("attr_zvalue");
            String fValue = jsonObject.optString("fuValue");

            // 显示数据
            GlideUtils.setRectImage(this, pic_info_url, ivGoodsPic);
            if (TextUtils.equals(mData_source, "huiguo")) {
                // 会过商品显示会过的商标
                String mark = "会过";
                String text = mark + " " + title;
                tvGoodsTitle.setText(
                        new SpannableEditor(this, text)
                                .setTextBgImage(R.drawable.will_self_text_bg, mark)
                                .setTextColor(R.color.homeWillText, mark)
                                .build());
                mOrderType = Constants.TYPE_HUIGUO;
            } else {
                // 自营商品显示自营的商标
                String mark = "自营";
                String text = mark + " " + title;
                tvGoodsTitle.setText(
                        new SpannableEditor(this, text)
                                .setTextBgImage(R.drawable.edinburgh_self_text_bg, mark)
                                .setTextColor(R.color.homeEdinburghSelfText, mark)
                                .build());
                mOrderType = Constants.TYPE_MEITIANHUI;
            }

            if (EmptyUtil.isEmpty(zValue)) {
                tvGoodsAttrs.setVisibility(View.INVISIBLE);
            } else {
                String attrs = EmptyUtil.isEmpty(fValue) ? zValue : (zValue + "/" + fValue);
                tvGoodsAttrs.setText(attrs);
            }

            // set goods money.
            String money = StringUtils.addRmbMark(mAmount);
            String moneyText = String.format(getString(R.string.submit_order_goods_money), money);
            tvGoodsMoney.setText(new SpannableEditor(this, moneyText)
                    .setTextColor(Color.parseColor("#ff4242"), money)
                    .build());
            // refresh money info.
            refreshShowMoney();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void refreshShowMoney() {
        tvGoodsNumber.setText(quantity);
        String prePay = StringUtils.addRmbMark(StringUtils.moneyMul(mAmount, quantity));
        String back = StringUtils.addRmbMark(StringUtils.moneyMul(StringUtils.moneySub(mAmount, discountPrice), quantity));
        String text = String.format(getString(R.string.submit_order_payment_info), prePay, back);

        tvPaymentInfo.setText(new SpannableEditor(this, text)
                .setTextColor(Color.parseColor("#ff4242"), prePay, back)
                .build());
        mTvSubmitPayable.setText(prePay);
    }

    @Override
    protected void onResume() {
        super.onResume();
        List<ConsumerAddress.ConsumerData> consumerDataListCache = InfoProvider.getUserReceivingAddress(this);
        if (consumerDataListCache != null) {
            if (consumerDataListCache.size() > 0) {
                for (int i= 0;i<consumerDataListCache.size();i++){
                    if(TextUtils.equals(consumerDataListCache.get(i).getIs_major_addr(),"Y")){
                        mTvSubmitAdsName.setText(consumerDataListCache.get(i).getConsignee());
                        mTvSubmitAdsPhone.setText(consumerDataListCache.get(i).getMobile());
                        String area = AddressUtil.getSSQ(this, consumerDataListCache.get(i).getArea_id());
                        String address = consumerDataListCache.get(i).getAddress();
                        mTvSubmitAdsAddress.setText(area + address);
                    }
                }
            } else {
                mTvSubmitAdsName.setText("");
                mTvSubmitAdsPhone.setText("");
                mTvSubmitAdsAddress.setText("");
            }
        }else {
            //从服务器拉取数据,暂时不写presenter
            Map<String, String> map = new HashMap<>();
            map.put("consumer_id", InfoProvider.getUserToken(this).getMember_id());
            MineApiDataSource.getInstance().getUserReceivingAddress(InfoProvider.getAppToken(this), "member.consumerAddressFind", new Gson().toJson(map)).subscribe(new ResponseObserver<ConsumerAddress>(this) {
                @Override
                public void onSuccess(ConsumerAddress data) {
                    List<ConsumerAddress.ConsumerData> consumerData= data.data;
                    if (consumerData.size() > 0) {
                        for (int i= 0;i<consumerData.size();i++){
                            if(TextUtils.equals(consumerData.get(i).getIs_major_addr(),"Y")){
                                mTvSubmitAdsName.setText(consumerData.get(i).getConsignee());
                                mTvSubmitAdsPhone.setText(consumerData.get(i).getMobile());
                                String area = AddressUtil.getSSQ(SubmitOrderActivity.this, consumerData.get(i).getArea_id());
                                String address = consumerData.get(i).getAddress();
                                mTvSubmitAdsAddress.setText(area + address);
                            }
                        }
                        //保存到本地
                        PreferenceUtils.saveObject(SubmitOrderActivity.this, Constants.USER_RECEIVING_ADDRESS,consumerData);
                    } else {
                        mTvSubmitAdsName.setText("");
                        mTvSubmitAdsPhone.setText("");
                        mTvSubmitAdsAddress.setText("");
                    }

                }
            });
        }
    }

    @Override
    public void call(View v) {
        super.call(v);
        switch (v.getId()) {
            case R.id.rl_submit_add_address:
                // 添加地址
                Intent intentAdd = new Intent(SubmitOrderActivity.this, ReceivingAddressActivity.class);
                startActivity(intentAdd);
                break;

            case R.id.tv_submit_go_pay:
                // 判断地址是否为空
                String address = mTvSubmitAdsAddress.getText().toString().trim();
                if (TextUtils.isEmpty(address)) {
                    TipUtils.showToast(App.getInstance(), "请填写收货地址", 3);
                    return;
                }
                String addressName = mTvSubmitAdsName.getText().toString().trim();
                if (TextUtils.isEmpty(addressName)) {
                    TipUtils.showToast(App.getInstance(), "请填写收货人名称", 3);
                    return;
                }
                String addressPhone = mTvSubmitAdsPhone.getText().toString().trim();
                if (TextUtils.isEmpty(addressPhone)) {
                    TipUtils.showToast(App.getInstance(), "请填写收货人联系方式", 3);
                    return;
                }
                // 获取留言
                String message = mTvSubmitMessage.getText().toString().trim();
                if (TextUtils.isEmpty(mOrderId)) {
                    //直接生成订单，点击去付款   StringUtils.moneyMul(mAmount,mCount)   +   mcount
                    mSubmitOrderPresenter.goToPayMoney(mPayWay, address, addressName, addressPhone,
                            message, mGoods_code, mOrderType, mAmount, mData_source, quantity, skuId, flags);
                } else {
                    //从订单界面点击过来付款   StringUtils.moneyMul(mAmount,mCount)
                    mSubmitOrderPresenter.callPay(mOrderId, mPayWay, mGoods_code, mAmount, mData_source);
                }
                break;

            case R.id.tv_submit_goods_minus:
                if (EmptyUtil.isEmpty(mOrderId)) {
                    int q = Integer.valueOf(quantity);
                    q -= 1;
                    if (q > 0) {
                        quantity = String.valueOf(q);
                        refreshShowMoney();
                    } else {
                        TipUtils.showToastLong(this, "购买数量不能为0");
                    }
                } else {
                    TipUtils.showToastLong(this, "购买数量不能为0");
                }
                break;

            case R.id.tv_submit_goods_plus:
                if (EmptyUtil.isEmpty(mOrderId)) {
                    int q = Integer.valueOf(quantity);
                    q += 1;
                    if (q <= Integer.valueOf(saleQty)) {
                        quantity = String.valueOf(q);
                        refreshShowMoney();
                    } else {
                        TipUtils.showToastLong(this, "超过库存数量");
                    }
                } else {
                    TipUtils.showToastLong(this, "超过限购数量");
                }
                break;
        }
    }

    private void initId() {
        mTvSubmitAdsName = getViewById(R.id.tv_submit_ads_name);
        mTvSubmitAdsPhone = getViewById(R.id.tv_submit_ads_phone);
        mTvSubmitAdsAddress = getViewById(R.id.tv_submit_ads_address);
        mRlSubmitAddAddress = getViewById(R.id.rl_submit_add_address);
        ivGoodsPic = getViewById(R.id.iv_submit_goods_pic);
        tvGoodsTitle = getViewById(R.id.tv_submit_goods_title);
        tvGoodsAttrs = getViewById(R.id.tv_submit_goods_attrs);
        tvGoodsMoney = getViewById(R.id.tv_submit_goods_money);
        tvGoodsNumber = getViewById(R.id.tv_submit_goods_number);
        ivGoodsMinus = getViewById(R.id.tv_submit_goods_minus);
        ivGoodsPlus = getViewById(R.id.tv_submit_goods_plus);
        mTvSubmitMessage = getViewById(R.id.tv_submit_message);
        tvPaymentInfo = getViewById(R.id.tv_submit_pay_info);
        mRbSubmitAlipay = getViewById(R.id.rb_submit_alipay);
        mRbSubmitWxpay = getViewById(R.id.rb_submit_wxpay);
        mRgOrderPay = getViewById(R.id.rg_order_pay);
        mTvSubmitPayable = getViewById(R.id.tv_submit_payable);
        mTvSubmitGoPay = getViewById(R.id.tv_submit_go_pay);

        RxUtils.bindEvents(mRlSubmitAddAddress, this);
        RxUtils.bindEvents(mTvSubmitGoPay, this);
        RxUtils.bindEvents(ivGoodsMinus, this);
        RxUtils.bindEvents(ivGoodsPlus, this);
    }

    @Override
    protected int setView() {
        return R.layout.activity_submit_order;
    }

    @Override
    protected void onRefreshData() {
    }


    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (checkedId) {
            case R.id.rb_submit_alipay:  //支付宝
                mPayWay = Constants.ALIPAY_APY;
                break;
            case R.id.rb_submit_wxpay:  //微信支付
                mPayWay = Constants.WECHAT_APY;
                break;
        }
    }

    @Override
    public void showError(String msg) {
    }

    @Override
    public void payMoneyFail(String msg) {
        TipUtils.showToast(App.getInstance(), msg, 3);
        if ("meitianhui".equals(mData_source)) {
            RxBus.get().post(new PayJumpBean("meitianhui"));
        } else {
            RxBus.get().post(new PayJumpBean("huiguo"));
        }
    }

    @Override
    public void payMoneySucc() {
        finish();
        if ("meitianhui".equals(mData_source)) {
            RxBus.get().post(new PayJumpBean("meitianhui"));
        } else {
            RxBus.get().post(new PayJumpBean("huiguo"));
        }
    }

}
